package com.ldl.servlet.demo;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.ldl.util.JsonUtil;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;

/**
 * @author Administrator
 * Author : L.D.L
 * E-mail : 1419485293@qq.com
 * Date : 2020年8月12日下午2:17:14
 */
@WebServlet("/demo/upload-1.let")
@MultipartConfig(
		maxFileSize = -1,
        maxRequestSize = -1
        )
public class Upload1Servlet extends HttpServlet{
	
	private Logger log = LoggerFactory.getLogger(this.getClass());

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		log.debug("文件上传开始");
		Map<String,Object> ret = new HashMap<String, Object>();
		try {
			File root = new File(getServletContext().getRealPath("/"));
			log.debug("获取网站的根目录：{}", root);

			String uri = "upload/"+ new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
			new File(root, uri).mkdirs();
			log.debug("创建保存文件的目录：{}", uri);

			Part img = request.getPart("img");// 获取上传的文件
			String ext = FileUtil.extName(img.getSubmittedFileName());
			log.debug("获取上传文件的扩展名：{}", ext);

			uri += UUID.randomUUID() + "." + ext;
			log.debug("保存的文件：{}", uri);
			log.debug("具体保存的文件：{}", new File(root, uri));
			img.write(new File(root, uri).toString());
			
			ret.put("ok", true);
			ret.put("uri", uri);
		} catch (Exception e) {
			log.warn("文件上传失败",e);
			ret.put("ok", false);
			ret.put("message", e.getMessage());
		}
		
		response.reset();
		response.setContentType("text/json;charset=UTF-8");
		response.getWriter().print(JSON.toJSONString(ret));
		response.flushBuffer();
		log.debug("文件上传结束");
	}
}
